<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;
use think\Session;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;
/**
 * 案場設備管理
 *
 * @icon fa fa-circle-o
 */
class Acdevice extends Backend
{
    
    /**
     * Acdevice模型对象
     * @var \app\admin\model\jdy\Acdevice
     */
    protected $model = null;

    const ANCHANG_ID = "__acdeviceanchangid__";

    protected $noNeedRight = ['drsb'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Acdevice;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $anchang_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            Session::set(self::ANCHANG_ID, $anchang_id);
        } else {
            Session::set(self::ANCHANG_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($anchang_id > 0) {
                $total = $this->model
                    ->with(['anchang','smallcategory'])
                    ->where($where)
                    ->where('anchang_id', $anchang_id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['anchang','smallcategory'])
                    ->where($where)
                    ->where('anchang_id', $anchang_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['anchang','smallcategory'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['anchang','smallcategory'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }


            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $anchang_id = 0;
        $anchangname = "";

        if (isset($_SERVER['REQUEST_URI']) && false !== strpos($_SERVER['REQUEST_URI'], '/ids/')) {
            $url = $_SERVER['REQUEST_URI'];
        } else {
            $url = $_SERVER['HTTP_REFERER'];
        }

        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchang_id = $urls[$size - 1];
            Session::set(self::ANCHANG_ID, $anchang_id);
            $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $anchang_id = Session::get(self::ANCHANG_ID);
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("anchangname", $anchangname);
        return $this->view->fetch();
    }

    public function drsb()
    {
        $anchang_id = Session::get(self::ANCHANG_ID);
        $list0 = $this->model
            ->where('anchang_id', $anchang_id)
            ->select();

        $sclist = \app\admin\model\jdy\Smallcategory::where('bigcategory_id', 4)->select();

        $dataset = [];
        foreach ($sclist as $row) {
            $find = 0;
            foreach ($list0 as $row0) {
                if ($row0->stype_id == $row->id) {
                    $find = 1;
                    break;
                }
            }
            if ($find == 0) {
                $dataset[] = ['anchang_id' => $anchang_id, 'stype_id' => $row->id, 'name' => $row->name];
            }
        }

        $this->model->saveAll($dataset);
        if (count($dataset) > 0) {
            $this->success("導入成功！");
        } else {
            $this->success("基礎設備已有，無需再導入！");
        }
    }

}
